// pages/order_detail/order_detail.js
var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
var mph = require("../../utils/util.js");
var key = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    pay_sn: '',
    psn:'',//拼团的团开团编号
    pay_type: 'wxpay_jsapi',
    address_data:null,
    she_yue:'',
    order_cont:null,
    // maxtime: 15 * 60,
    maxtime: 15 * 60,
    timemsg:'00:00',
    timer:null,
    order_goods_type:'',
    order_id:''
  },
////////////////////////////////////////////
  /** 是否选择余额支付,验证支付密码是否正确
  */
  load_pass: function (pwd) {
    var that = this;
    var datas = wx.getStorageSync('order_parameter');
    let address_data = datas.address_data;
    that.setData({
      address_data: address_data
    });

    if (datas.yue && pwd) {
      var url = "index.php?act=member_buy&op=check_pd_pwd";
      mph.postRequest(url, { password: pwd}, function (res) {
        if (res.data.code == 200) {
          that.buy_step2(pwd);
          console.log('余额支付');
        }
      },'/pages/my_order/my_order')
    } else {
      console.log('微信支付');
      that.buy_step2(pwd);
    }

  },
  //立即购买第二步，下单 index.php?act=member_buy&op=buy_step2
  /** 
   * 获取商品相关数据
   */
  buy_step2: function (pwd) {
    var that = this;
    // var data = that.data;
    var datas = wx.getStorageSync('order_parameter');

    console.log('系统变量', datas);
    var data = {
      ifcart: datas.ifcart,
      cart_id: datas.cart_id,
      address_id: datas.address_data.address_id,
      offpay_hash: datas.address_api.offpay_hash,
      offpay_hash_batch: datas.address_api.offpay_hash_batch,
      vat_hash: datas.step1.vat_hash,
      pay_name: 'online',
      psn: datas.psn,
      points: datas.points,
      voucher: datas.vouchers,
      goods_flag: datas.goods_flag,
      goods_gift_flag: datas.goods_gift_flag,
      pd_pay: datas.yue ? 1 : 0,
      password: pwd
    };
    var url = '/index.php?act=member_buy&op=buy_step2';
    mph.postRequest(url, data,
      function (res) {
        if (res.data.code == 200) {

          console.log('buy_step2获取商品相关数据:===>',res.data.datas,);
          console.log('buy_step2获取商品相关数据:===>', res.data.datas.info.order_list);

          let json = res.data.datas.info.order_list;
          let arr = [];

          for (var key in json){
            arr.push(key);
          }

          if (arr.length>1){

          }else{
            that.order_info(arr[0]);
          }


          that.setData({
            pay_sn: res.data.datas.pay_sn
          });
          that.buy_pay(res.data.datas.pay_sn);
        }
      })
  },
  /** 选择支付
  */
  buy_pay: function (pay_sn) {
    console.log(pay_sn);
    var that = this;
    var pay = { 'pay_sn': pay_sn }
    var url = '/index.php?act=member_buy&op=pay';
    mph.post1Request(url, pay,
      function (res) {
        if (res.data.code == 200) {
          var data = res.data.datas;
          that.load_yue(data.pay_info);
        } else if (res.data.code == 400) {//订单支付完成,没有订单,都跳转
          that.go_to_order('');
        }
      })
  },
  /** 验证预付款是否可以进行
  */
  load_yue: function (e) {
    // console.log('预付',e)
    var that = this;
    //没设置支付密码，去设置
    if (e.member_paypwd == false) {
      wx.navigateTo({
        url: '/pages/set_password/set_password?type=paypwd'
      })
      return false;
    }
    //已经支付完成
    if (e.pay_amount <= 0) {
      console.log(e, 5555);
      that.go_to_order('');
    }

    //调用微信支付支付剩余款项
    var flag = false;
    for (var i = 0; i < e.payment_list.length; i++) {
      if (e.payment_list[i].payment_code == that.data.pay_type) { flag = true; break; }
    };

    if (flag == false) {
      wx.showToast({
        title: '支付失败',
        icon: 'none',
        duration: 2000
      })
      that.go_to_order('state_new');
    }
    that.pay_new()

  },
  /** 去支付
  */
  pay_new: function () {
    var that = this;
    var url = 'index.php?act=member_payment&op=pay_xcx';
    var data = {
      pay_sn: that.data.pay_sn,
      password: '',
      rcb_pay: 0,
      pd_pay: 0,
      payment_code: that.data.pay_type
    }
    console.log(data,909090);
    mph.postRequest(url, data, function (e) {
      console.log(44444444444444, e)
      if (e.data.code == 200) {
        var data = e.data.datas;
        console.log(1112223344, data)
        wx.requestPayment(
          {
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': 'MD5',
            'paySign': data.paySign,
            'success': function (res) {//支付成功后执行
              console.log('支付成功后执行:=========>', res)
              clearInterval(that.data.timer);
              
              that.go_to_order('');
            },
            'fail': function (res) { console.log(222, res) },
            'complete': function (res) { console.log(333, res) }
          })

      }
    })
  },
////////////////////////////

  //跳转到订单列表页面
  go_to_order: function (name) {
    console.log('跳转到订单列表页面:==>',this.data.order_goods_type);
    if (this.data.order_goods_type == "groupbuy") {
      wx.redirectTo({
        url: '/pages/group_details/group_details?psn=' + this.data.order_id+'&type=3'
      })

      // wx.setStorageSync('', this.data.order_cont);
    } else {
      wx.redirectTo({
        url: '/pages/my_order/my_order?name=' + name
      })
    }
  },
  //点击支付按钮
  go_zhifu:function(){
    if (this.data.she_yue) {
      this.showInputLayer();//支付密码弹出框！！！
    } else {
      this.pay_new();
    }
  },
  //取消订单
  cancellation_of_order:function(){
    var that = this;
    let k = wx.getStorageSync('key');
    let order_id = that.data.order_cont.order_id;
    // wx.showModal({
    //   title: '',
    //   content: '确定要取消订单',
    //   success: function (res) {
    //     if (res.confirm) {

          wx.request({
            url: ApiUrl + "/index.php?act=member_order&op=order_cancel",
            data: { 'key': k, 'order_id': order_id },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'post',
            success: function (res) {
              console.log('取消订单:===>',res);
              if (res.data.datas == 1) {
                clearInterval(that.data.timer);
                wx.showToast({
                  title: '取消成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.redirectTo({
                  url: '/pages/order_detail/order_detail?order_id=' + order_id + "&key=" + key,
                })
              }else{
                wx.showToast({
                  title: res.data.datas,
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        // }
    //   }
    // })
  },
  //订单详情
  order_info: function (order_id) {
    var that = this;
    let k = wx.getStorageSync('key');
    console.log(k,order_id);
    var pay = { key: k, order_id: order_id }
    var url = '/index.php?act=member_order&op=order_info';
    mph.getRequest(url, pay,
      function (res) {
        console.log(res);
        if (res.data.code == 200) {
          var data = res.data.datas.order_info;
          console.log('订单详情:===>',data);

          // address_data
          let obj = {
            address: data.reciver_addr,
            true_name: data.reciver_name,
            mob_phone: data.reciver_phone,
          }


          that.setData({ 
            order_cont: data,
            address_data: obj,
            order_goods_type: data.order_goods_type,
            order_id: data.order_id
          });
          if (data.state_desc == '待付款') {
            that.daojishi();
            clearInterval(that.data.timer);
            that.data.timer = setInterval(function () {
              that.daojishi();
            }, 1000); 
          } 
        } 
      })
  },
  //字符串加0函数
  strPlus0(s){
    return s<10?'0'+s:''+s;
  },
  //15分钟订单倒计时
  daojishi(){
    if (this.data.maxtime >= 0) {
      let minutes = Math.floor(this.data.maxtime / 60);
      let seconds = Math.floor(this.data.maxtime % 60);
      let timemsg = this.strPlus0(minutes) + ":" + this.strPlus0(seconds);
      this.setData({
        timemsg: timemsg
      });
      // if (maxtime == 5 * 60) alert("距离结束仅剩5分钟");
      this.data.maxtime--;
      console.log(this.data.maxtime);
    } else {
      this.cancellation_of_order();
      clearInterval(this.data.timer);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('监听页面加载===>',options);
    let that = this;
    if (options.order_id){
      that.order_info(options.order_id);//pay_sn
      that.setData({ pay_sn: options.pay_sn })

    } else {

      if (options.yue) {
        that.setData({ she_yue: options.yue });
        that.showInputLayer();//支付密码弹出框！！！
        // that.order_info(options.zdygoodsId);
      } else {
        that.load_pass();
        console.log('一进来就微信支付');
      }
      
    }
  }, 
  /**
    * 显示支付密码输入层
    */
  showInputLayer: function () {
    this.setData({ showPayPwdInput: true, payFocus: true });
  },
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {
    let that = this;
    var val = that.data.pwdVal;
    that.setData({ showPayPwdInput: false, payFocus: false, pwdVal: '' }, function () {
      that.load_pass(val);
      // wx.showToast({
      //   title: val,
      // })
    });

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });

    if (e.detail.value.length >= 6) {
      this.hidePayLayer();
    }
  },
  //全部退款
  /*refund_order: function (result) {
    key = result.currentTarget.dataset.key;
    var order_id = result.currentTarget.dataset.order_id;
    wx.showModal({
      title: '',
      content: '确定要取消订单',
      success: function (res) {
        if (res.confirm) {

          wx.request({
            url: ApiUrl + "/index.php?act=member_order&op=order_cancel",
            data: { 'key': key, 'order_id': order_id },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'post',
            success: function (res) {
              if (res.data.datas == 1) {
                wx.showToast({
                  title: '取消成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.redirectTo({
                  url: '/pages/order_detail/order_detail?order_id=' + order_id + "&key=" + key,
                })
              }
            }
          })
        }
      }
    })
  }, */
})